﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebHoiChoMuaBan.Controllers.Helpers;
using WebHoiChoMuaBan.Controllers.Global;
using WebHoiChoMuaBan.Models;
using WebHoiChoMuaBan.Controllers.Utility;
using System.Drawing;
using System.IO;

namespace WebHoiChoMuaBan.Controllers.Private
{
    public class NewsController : PrivateController
    {
        //
        // GET: /News/

        private void Init()
        {
            ViewData["mid"] = "news";
            LoadTimeAndCurrency();
        }

        public ActionResult List(int? uid)
        {
            int pageNum = 0;
            if (uid == null)
                return HomePage();

            if (Request.QueryString["p"] == null)
                pageNum = 1;
            else
                pageNum = int.Parse(Request.QueryString["p"]);
            if (LoadMember(uid.Value) == null)
            {
                Init();
                NewsHelper newsHelper = new NewsHelper(uid.Value);
                ViewData["ListNews"] = newsHelper.getListNews(pageNum, Config.ITEMS_PER_PAGE);
                return View("~/Views/Private/NewsList.aspx");
            }
            return HomePage();
        }
        
        public RedirectResult AddComment(FormCollection form)
        {
            if (Session["MemId"] != null)
            {
                string content = (string)form["txtComment"];
                string newsIdStr = form["newsId"];
                string comIdReplyStr = form["IsReplyTo"];
                int memberId = (int)Session["MemId"];
                int newsId, comIdReply;
                ChatHelper chat = new ChatHelper();
                List<ChatEmotionDetail> emos = chat.getEmotionPath();
                foreach (ChatEmotionDetail emo in emos)
                {
                    content = content.Replace(emo.notation, "<img src='" + emo.path + "' width='40px' height='40px'/>");
                }
                if (int.TryParse(newsIdStr, out newsId))
                {
                    NewsHelper hNews = new NewsHelper();
                    if (int.TryParse(comIdReplyStr, out comIdReply))
                        hNews.AddComment(content, newsId, memberId, comIdReply);
                    else hNews.AddComment(content, newsId, memberId, null);
                }
                else ViewData["ErrorMsg"] = "Error";
            }
            return Redirect(Request.UrlReferrer.AbsoluteUri + "#comments");
        }

        //
        // GET: /News/Detail/5/title-of-article
        //public ActionResult Detail(int? uid, int newsId, string title)
        [HttpGet]
        public ActionResult Detail(int? uid, int newsId)
        {
            if (LoadMember(uid.Value) == null)
            {
                Init();
                NewsHelper newsHelper = new NewsHelper(uid.Value);
                ViewData["NewsDetail"] = newsHelper.myGetNewsById(newsId);
                ViewData["ListNewNews"] = newsHelper.GetNewsByNewsTypeId(newsId, Config.NEW_NEWS_PER_PAGE);
                //ViewData["OtherNews"] = newsHelper.GetOtherNews(uid.Value, Config.OTHER_NEWS_PER_PAGE);
                return View("~/Views/Private/NewsDetail.aspx");
            }
            return HomePage();
        }

        [ValidateInput(false)]
        public ActionResult Create(int? uid)
        {
            if (!this.IsLogin || uid == null)
                return HomePage();
            Init();
            if (LoadMember(uid.Value) == null)
            {
                NewsTypeHelper newsTypeHelper = new NewsTypeHelper();
                ViewData["ListNewsType"] = newsTypeHelper.GetAllNewsType();
                return View("~/Views/Private/PostNews.aspx");
            }
            return HomePage();

        }

        [HttpPost, ValidateInput(false)]
        public ActionResult Create(FormCollection f, HttpPostedFileBase newsImg)
        {
            int? uid = (int?)Session["MemId"];
            if (!this.IsLogin || uid == null)
                return HomePage();
            Init();
            if (LoadMember(uid.Value) == null)
            {
                News news = new News();
                news.NewsTitle = f.Get("txtTitle");
                news.NewsIntro = f.Get("txtIntro");
                news.NewsContent = f.Get("txtContent");
                news.NewsDate = DateTime.Now;
                news.NewsState = true;
                if (newsImg != null)
                {
                    ImageHelper imgHelper = new ImageHelper();
                    if (imgHelper.CheckInfoIcon(newsImg))
                    {
                        string imgName = "thumbnail_" + newsImg.FileName;
                        news.NewsThumb = imgName;
                        Bitmap image = imgHelper.ResizeImage(newsImg.InputStream, 200, 100);
                        var path = Path.Combine(Server.MapPath("~/Content/Images/Upload/Thumbnail/"), imgName);
                        image.Save(path);
                        image.Dispose();
                    }
                }
                //Phân loại tin mới được tạo 
                news.NewsTypeId = int.Parse(f.Get("lstNewsType"));
                //Tin được tạo bởi member nào
                news.MemId = (int)Session["MemId"];

                ViewData["News"] = news;
                if (news.IsValid)
                {
                    NewsHelper newsHelper = new NewsHelper();
                    newsHelper.Add(news);
                    newsHelper.Save();
                    //Reset lại các trường ban đầu
                    ViewData["News"] = null;
                    return RedirectToAction("Create", "News");
                }
                else
                {
                    foreach (var issue in news.GetRuleViolations())
                    {
                        ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
                    }
                }
                return View("~/Views/Private/PostNews.aspx");
            }
            return HomePage();
        }

        //
        // GET: /News/Edit/5

        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /News/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /News/Delete/5

        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /News/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        public ActionResult AdList(int? uid, int? page)
        {
            return View("~/Views/Private/AdList.aspx");
        }

        public ActionResult ProductDetail(int? newsId, string title)
        {
            return View("~/Views/Private/ProductDetail.aspx");
        }

        public ActionResult ProductCreate()
        {
            return View("~/Views/Private/ProductCreate.aspx");
        }

        public ActionResult ProductList(int? uid)
        {
            return View("~/Views/Private/ProductList.aspx");
        }

        public ActionResult RealEstateCreate()
        {
            return View("~/Views/Private/RealEstateCreate.aspx");
        }

        [HttpPost]
        public string Like(string proId)
        {
            if (Session["MemId"] == null)
                return "null";
            News pro = new NewsHelper().GetNewsById(int.Parse( proId));
            pro.NewsLike = pro.NewsLike + 1;
            bool isSuccess = new NewsHelper().SaveNews(pro, Session["MemId"] + "");
            if (isSuccess)
                return pro.NewsLike + "";
            else
                return "duplicated";

        }
    }
}
